from enum import Enum
from django.db import models
from django.core.validators import EmailValidator, URLValidator
from django.core.exceptions import ValidationError
from user.models import User
from logs.models import convert_us_to_china_time

class Link(models.Model):
    LinkId = models.AutoField(
        primary_key=True,
        verbose_name="链接ID",
        help_text="系统自动生成的唯一标识"
    )
    # 添加用户关联字段
    user = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        null=True,
        blank=True,
        related_name='links',
        verbose_name="关联用户",
        help_text="创建该链接的用户"
    )
    MCCName = models.CharField(
        max_length=150,
        verbose_name="MCC 名称",
        help_text="广告客户中心 (MCC) 的名称"
    )
    UserEmail = models.EmailField(
        max_length=255,
        verbose_name="用户邮箱",
        help_text="用户的邮箱地址",
        validators=[EmailValidator(message="邮箱格式无效")]
    )
    MCCAccount = models.CharField(
        max_length=100,
        verbose_name="MCC 账号",
        help_text="广告客户中心 (MCC) 的账号名称"
    )
    GoogleAccount = models.CharField(
        max_length=100,
        verbose_name="Google 账号",
        help_text="与 MCC 关联的 Google 账号名称"
    )
    CampaignName = models.CharField(
        max_length=200,
        verbose_name="活动名称",
        help_text="广告活动的名称"
    )
    finalUrl = models.URLField(
        max_length=500,
        verbose_name="最终链接",
        help_text="广告的最终跳转链接",
        validators=[URLValidator(message="无效的链接格式")]
    )
    OfferLink = models.URLField(
        max_length=500,
        verbose_name="优惠链接",
        help_text="与广告相关的优惠链接",
        validators=[URLValidator(message="无效的链接格式")]
    )
    redirect = models.IntegerField(
        default=0,
        verbose_name="重定向",
        help_text="重定向的目标 ID，默认为 0"
    )
    fail_num = models.IntegerField(
        default=0,
        verbose_name="失败次数",
        help_text="失败次数，超过五次则关闭运行，默认为 0"
    )
    TargetNation = models.CharField(
        max_length=100,
        verbose_name="目标国家",
        help_text="广告投放的目标国家或地区"
    )
    URLldentifiers = models.TextField(
        verbose_name="URL 标识符",
        help_text="与链接相关的唯一标识符"
    )
    referrer = models.URLField(
        max_length=500,
        verbose_name="来源页面URL",
        help_text="设置HTTP Referrer头的URL，可用于伪装来源页面",
        null=True,
        blank=True
    )
    # IP = models.GenericIPAddressField(
    #     verbose_name="IP 地址",
    #     help_text="广告活动的源 IP 地址",
    #     null=True,
    #     blank=True
    # )
    InterVal = models.IntegerField(
        default=10,
        verbose_name="时间间隔",
        help_text="运行时间间隔 ，默认为 10 分钟"
    )
    Swith = models.BooleanField(
        default=True,
        verbose_name="开关",
        help_text="广告活动的开关状态, 默认为开启"
    )

    finalUpdateTime = models.DateTimeField(
        verbose_name="最后更新时间",
        help_text="记录最后更新时间",
        auto_now=True,
    )
    # 时间间隔
    # 设置开关
    class Meta:
        verbose_name = "链接"
        verbose_name_plural = "链接管理"

    def __str__(self):
        return self.CampaignName

    def validate_email(self):
        """
        校验用户邮箱格式是否合法。
        """
        try:
            EmailValidator(message="邮箱格式无效")(self.UserEmail)
            return True
        except ValidationError:
            return False
        
    class SwitchChoices(Enum):
        TRUE = "启动"
        FALSE = "关闭"

        @classmethod
        def choices(cls):
            return [(choice.value, choice.name.capitalize()) for choice in cls]



    def to_dict(self):
        status=""
        if self.Swith:
            status = "更新成功"
        elif not self.Swith and self.fail_num < 5:
            status = "手动暂停"
        elif not self.Swith and self.fail_num == 5:
            status = "强制暂停"

        return {
            "LinkId": self.LinkId,
            "userId": self.user.userId if self.user else None,
            "MCCName": self.MCCName,
            "UserEmail": self.UserEmail,
            "MCCAccount": self.MCCAccount,
            "GoogleAccount": self.GoogleAccount,
            "CampaignName": self.CampaignName,
            "finalUrl": self.finalUrl,
            "OfferLink": self.OfferLink,
            "redirect": self.redirect,
            "TargetNation": self.TargetNation,
            "URLldentifiers": self.URLldentifiers,
            "referrer": self.referrer,
            "InterVal": self.InterVal,
            "Swith": self.Swith,
            "note": status,
            "finalUpdateTime": convert_us_to_china_time(self.finalUpdateTime.isoformat())
        }
